package com.yilouwangye.proxy.exmple_3;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

// 自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
    // 被代理的类
    private CardImpl card;

    public void setCard(CardImpl card) {
        this.card = card;
    }
    // 生成得到代理类
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(), card.getClass().getInterfaces(),this);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 动态代理的本质，使用反射机制
        save();
        Object result = method.invoke(card,args);
        shop();
        return result;
    }
    public void save(){
        System.out.println("存钱功能");
    }
    public void shop(){
        System.out.println("购物功能");
    }
}
